//app.js 在这里写接口
import config from './config'
// 取API的接口
const API = config.api

App({
    httpIdx: 0,
    systemInfo: '',
    networkType: '', //手机网络
    isIndex: false,
    onLaunch: function () {
        // 展示本地存储能力
    var logs = wx.getStorageSync('logs') || []
    logs.unshift(Date.now())
    wx.setStorageSync('logs', logs)
    const systemInfo = wx.getSystemInfoSync(); //获取系统信息
    const menuInfo = wx.getMenuButtonBoundingClientRect(); // 获取胶囊按钮的信息
    this.globalData.menuHeight = menuInfo.height; // 获取胶囊按钮的高
    this.globalData.statusBarHeight = systemInfo.statusBarHeight; // 获取状态栏的高
    this.globalData.menuRight = menuInfo.right; // 获取胶囊按钮的距离屏幕最右边的距离（此处用于设置导航栏左侧距离屏幕的距离）
    this.globalData.navBarHeight = (menuInfo.top - systemInfo.statusBarHeight) * 2 + menuInfo.height; // 计算出导航栏的高度
        this.updateApp(); // 强制更新版本
        // 获取设备信息
        this.getSystemInfo();
        this.checkNetworkType();
        wx.showShareMenu({
            withShareTicket: true,
            menus: ['shareAppMessage', 'shareTimeline']
        })
        this.overShare();
        this.globalData.token = wx.getStorageSync('token') || '';
        wx.checkSession({
            success: () => {
                this.globalData.user_id = wx.getStorageSync('user_id') || '';
                this.globalData.openid = wx.getStorageSync('openid') || '';
                this.globalData.token = wx.getStorageSync('token') || '';
            },
            fail() {}
        })
        // 这是一个Promise 获取成功之后的数据返回这里
        this.getDeviceSize().then(res => {
            const {
                bottomLift
            } = res
            // 这些 底部高度bottomLift 窗口高度windowHeight  这里应该是状态栏高度statusBarHeight  CustomBar 
            // console.log(res,'刚刚返回的对象');  
            this.globalData.bottomLift = bottomLift
        })

    },
    globalData: {
      navBarHeight:0,// 导航栏高度
      menuHeight:0,//胶囊按钮 高度
      statusBarHeight:0,//状态栏高度
      menuRight:0,//胶囊按钮 距离屏幕右边的距离
        extraData: '',
        wxUserState: 'NORMAL',
        wxTradeScene: '',
        isGetWxToken: false,
        _userInfo: null,
        userInfo: null,
        user_id: '',
        indexJS: null,
        token: '',
        openid: '',
        ETCRegisterInfo: {
            apply: {},
            idcard: {},
            vehiclelicense: {},
        }
    },
    updateApp() {
        let t = this;
        const updateManager = wx.getUpdateManager()
        updateManager.onCheckForUpdate(function (res) {
            // 请求完新版本信息的回调
            if (res.hasUpdate) {
                wx.clearStorageSync();
                wx.clearStorage();
                this.globalData.user_id = ''
                wx.showLoading({
                    title: '更新下载中',
                })
            }
        })
        updateManager.onUpdateReady(function () {
            wx.hideLoading();
            wx.clearStorageSync();
            wx.clearStorage();
            this.globalData.user_id = ''
            // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
            // updateManager.applyUpdate()
            wx.showModal({
                title: '更新提示',
                content: '新版本已下载完毕，准备更新',
                showCancel: false,
                success: function (res) {
                    if (res.confirm) {
                        // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
                        updateManager.applyUpdate()
                    }
                }
            })
        })
        updateManager.onUpdateFailed(function () {
            this.globalData.user_id = ''
            wx.clearStorageSync();
            wx.clearStorage();
            // 新的版本下载失败
            wx.hideLoading();
            wx.showModal({
                title: '更新提示',
                content: '新版本下载失败',
                showCancel: false
            })
        })
    },

    getDeviceSize: function () {
        return new Promise((resolve, reject) => {
            // 获取设备信息
            wx.getSystemInfo({
                success: function (res) {
                    // console.log(res)
                    const {
                        // 屏幕高度 整个屏幕的高度 = windowHeight + statusBarHeight + safeArea + titleBarHeight  
                        screenHeight,
                        //高度对象
                        safeArea,
                        // 窗口高度 能看到的部分 
                        windowHeight,
                        // 状态栏高度 
                        statusBarHeight
                    } = res
                    // console.log(res,"获取高度信息");
                    let custom = wx.getMenuButtonBoundingClientRect();
                    // 计算公式 
                    const CustomBar = custom.bottom + custom.top - res.statusBarHeight;
                    const {
                        bottom
                    } = safeArea
                    // 底部高度  
                    const bottomLift = screenHeight - bottom
                    // 成功后返回 底部高度bottomLift 窗口高度windowHeight  这里应该是状态栏高度statusBarHeight  CustomBar 
                    resolve({
                        bottomLift,
                        windowHeight,
                        statusBarHeight,
                        CustomBar
                    })
                }
            })
        })
    },
    getSystemInfo() {
        wx.getSystemInfo({
            success: e => {
                // 这个获取高度信息保存起来
                this.globalData.StatusBar = e.statusBarHeight;
                let custom = wx.getMenuButtonBoundingClientRect();
                this.globalData.Custom = custom;
                this.globalData.CustomBar = custom.bottom + custom.top - e.statusBarHeight;
                this.globalData.platform = e.platform;
                this.globalData.px = e.pixelRatio
                this.systemInfo = e;
            }
        })
    },
    watch(method) {
        var obj = this.globalData;
        Object.defineProperty(obj, "userInfo", {
            configurable: true, //描述属性是否配置，以及可否删除 false 时，不能删除当前属性，且不能重新配置当前属性的描述符(有一个小小的意外：true时，可以删除当前属性，可以配置当前属性所有描述符。
            enumerable: true, //描述属性是否会出现在for in 或者 Object.keys()的遍历中
            set: function (value) {
                this._userInfo = value;
                console.log('是否会被执行2')
                method(value);
            },
            get: function () {
                // 可以在这里打印一些东西，然后在其他界面调用getApp().globalData.chatList的时候，这里就会执行。
                return this._userInfo
            }
        })
    },
    //重写分享方法

    overShare: function () {

        let _this = this

        //间接实现全局设置分享内容

        wx.onAppRoute(function (res) {

            //获取加载的页面

            let pages = getCurrentPages(),
                view = pages[pages.length - 1],
                data;
            if (view) {
                data = view.data;
                if (!data.isOverShare) {
                    data.isOverShare = true;
                    view.onShareAppMessage = function () {
                        //重写分享配置
                        return {
                            title: '畅行全国高速，从这里开始',
                            path: '/pages/index/index',
                            imageUrl: 'https://yxyt.oss-cn-hangzhou.aliyuncs.com/ghac/2022111500001.jpg'
                        }
                    }
                }
            }
        })

    },
    onShow(options) {
        if (this.globalData.isGetWxToken) {
            if (options.path == 'attractInvestment/pages/etcBid/etcBid' && options.scene == 1038) {
                if (options.referrerInfo && options.referrerInfo.extraData) {
                    this.globalData.wxUserState = options.referrerInfo.extraData.wxUserState
                    this.globalData.extraData = JSON.stringify(options.referrerInfo.extraData)
                    this.globalData.wxTradeScene = options.referrerInfo.extraData.wxTradeScene
                } else {
                    this.globalData.wxUserState = ''
                    this.globalData.extraData = ''
                    this.globalData.wxTradeScene = ''
                }

            } else {
                this.globalData.wxUserState = ''
                this.globalData.extraData = ''
                this.globalData.wxTradeScene = ''
            }
        } else {
            this.globalData.extraData = ''
            this.globalData.wxUserState = ''
            this.globalData.wxTradeScene = ''
        }
    },
    // 登录
    login(res) {
        wx.showLoading({
            title: '登录中...',
            mask: true
        });
        return new Promise((resolve, reject) => {
            // 登录接口 
            this.http(API.login, {
                code: res.code,
                encryptedData: res.encryptedData,
                iv: res.iv,
                carBrand: 0
            }).then(resp => {
                if (resp.code == 200) {
                    console.log('登录返回：', resp)
                    // resp.data.userId = '97145915468152832'
                    // wx.setStorageSync("userId", '98871617963950080');
                    // wx.setStorageSync("phoneNumber", '13635678729');
                    // wx.setStorageSync("openid", 'oPdgQ5uZ7MVTv_HIpQSR2oMW0mCU');


                    wx.setStorageSync("userId", resp.data.userId);
                    wx.setStorageSync("phoneNumber", resp.data.phoneNumber);

                    wx.setStorageSync("token", resp.data.tokenHead + resp.data.token);
                    wx.setStorageSync("openid", resp.data.openid);
                    setTimeout(res => {
                        resolve(resp.data)
                        wx.showToast({
                            title: '登陆成功'
                        });
                        wx.navigateTo({
                          url: '/pages/apply/apply',
                        })
                    }, 300)
                    // console.log('登陆成功', resp)
                } else {
                    reject()
                    wx.showToast({
                        title: '登陆失败',
                        icon: 'none'
                    });
                }
            }).catch(err => {
                reject()
                wx.showToast({
                    title: '登陆失败',
                    icon: 'none'
                });
            })
        })

    },
    // 使用Promise方式请求
    // console.log(`%cReq ${api}%c${new Date()}\n%c${JSON.stringify(data)}  ${JSON.stringify(options)}`, "padding: 0 4px 1px 4px; border-top-left-radius: 3px; border-bottom-left-radius: 3px; color: yellow; background: #003300; ", "margin-right: 4px; padding: 0 4px 1px 4px; border-top-right-radius: 3px;  border-bottom-right-radius: 3px; color: yellow; background: #008800;", "")
    // 这些参数相应按顺序传   
    // const API = config.api
    http(api, data = {}, options = {}, contentType = 'application/json', miniApi = false) {
        // 存储登录的token
        let token = wx.getStorageSync('token');
        // url拼接
        const base = {
            os: 'mini',
            d_brand: this.systemInfo.brand,
            d_model: this.systemInfo.model,
            osVersion: this.systemInfo.system,
            osVersion: this.systemInfo.system,
            clientVersion: this.systemInfo.version,
            info: this.systemInfo,
            networkType: this.networkType,
        };
        return new Promise((resolve, reject) => {
            // 这里是重点 wx.request发起请求
            wx.request({
                // 判断是否返回条件进行url拼接
                url: miniApi ? config.baseUrl2 + api : config.baseUrl + api,
                // 是否有传入请求类名，默认Post
                method: options.method || 'POST',
                // 这里是传入的参数data
                data: {
                    // 一般后端相应JSON格式，这里转JSON
                    base: JSON.stringify(base),
                    // 将剩下的参数全部传入
                    ...data
                },
                // 请求头 
                header: {
                    "Authorization": token,
                    "content-type": contentType
                },
                // 请求成功回调
                success: (res) => {
                    if (res.data.code == '522' || res.data.code == '521') {
                        if (this.httpIdx >= 2) {
                            this.httpIdx = 0
                            resolve(res.data)
                        } else {
                            setTimeout(res => {
                                this.httpIdx++
                                resolve(this.http(api, data, options, contentType))

                            }, 2000)
                        }

                    } else {
                        this.httpIdx = 0
                        if (res.data.code == '401') {
                            if (!this.isIndex) {
                                wx.clearStorageSync();
                                wx.clearStorage();
                                wx.showModal({
                                    title: '提示',
                                    content: '登陆失效，请返回首页进行授权登陆',
                                    showCancel: false,
                                    success(res) {
                                        wx.redirectTo({
                                            url: '/pages/index/index',
                                        })

                                    }
                                })
                                this.isIndex = true;

                            }

                        } else {
                            resolve(res.data)
                        }

                    }
                    // console.log(`%cReq ${api}%c${new Date()}\n%c${JSON.stringify(data)}  ${JSON.stringify(options)}`, "padding: 0 4px 1px 4px; border-top-left-radius: 3px; border-bottom-left-radius: 3px; color: yellow; background: #003300; ", "margin-right: 4px; padding: 0 4px 1px 4px; border-top-right-radius: 3px;  border-bottom-right-radius: 3px; color: yellow; background: #008800;", "")

                },
                // 请求失败回调
                fail: (res) => {
                    wx.showToast({
                        title: '请求超时',
                        icon: 'none'
                    })
                    this.httpIdx = 0
                    reject(res)
                }
            })
        })
    },
    //检测网络类型
    checkNetworkType() {
        let _this = this;
        wx.getNetworkType({
            success: function (res) {
                // 返回网络类型, 有效值：
                // wifi/2g/3g/4g/unknown(Android下不常见的网络类型)/none(无网络)
                var networkType = res.networkType;
                _this.networkType = res.networkType;
                if (networkType == 'none' || networkType == 'unknown') {
                    wx.showToast({
                        title: '您的网络环境有问题，请检查是否已连接网络',
                        icon: 'none'
                    })
                } else if (networkType == '2g') {
                    wx.showToast({
                        title: '您现在处于2g网络下',
                        icon: 'none'
                    })
                }
            }
        })
    },

})